package com.itheima.reggie.handler;

import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice // 全局异常捕获，底层AOP
@Slf4j
public class GlobalExceptionHandler {



    // 预期内，自定义业务异常
    @ExceptionHandler(CustomException.class)
    public ResultInfo customeExceptionHandler(CustomException ce){
        ce.printStackTrace();
        return ResultInfo.error(ce.getMessage());
    }

    // 预期内，重复命名的异常
    @ExceptionHandler(DuplicateKeyException.class)
    public ResultInfo duplicateKeyExceptionHandler(DuplicateKeyException dke){
        dke.printStackTrace();
        return ResultInfo.error("此名称已被使用，请更换一个");
    }

    // 非预期异常
    @ExceptionHandler(Exception.class)
    public ResultInfo exceptionHandler(Exception ex) {
        // log.error(ex.getMessage());
        ex.printStackTrace();
        return ResultInfo.error("服务器繁忙，请稍后重试");
    }
}
